#include <iostream>
#include <stdexcept>
#include <cstdlib>
#include <strings.h>

#include "ArgsParser.h"

#if _MSC_VER
#	define strcmpi _strcmpi
#	define strnicmp _strnicmp
#elif __GNUC__
#	define strcmpi strcasecmp
#	define strnicmp strncasecmp
#endif

using namespace std;


ArgsParser::ArgsParser(int argc, const char *argv[])
{
	SetDefault();

	// Checking "benchmark ping_pong".
	if (argc == 2)
	{
		if (strcmpi(argv[1], "ping_pong") == 0)
		{
			_isPingPongServer = true;
		}
		else
		{
			PrintHelp();
			throw invalid_argument("Wrong command line arguments");
		}

		return;
	}

	// Checking "benchmark host_name connection_count [-port:number] [-sync] [-pingpong]".
	for (int argn = argc - 1; argn > 2; --argn)
	{
		if (strcmpi(argv[argn], "-sync") == 0)
		{
			_isSync = true;
		}
		else if (strcmpi(argv[argn], "-pingpong") == 0)
		{
			_isPingPongClient = true;
		}
		else if (strnicmp(argv[argn], "-port:", 6) == 0)
		{
			_port = atoi(argv[argn] + 6);
		}
		else
		{
			PrintHelp();
			throw invalid_argument("Wrong command line arguments");
		}
	}
		
	if (argc >= 3)
	{
		_connectionCount = atoi(argv[2]);
		_hostName = argv[1];
	}
	else
	{
		PrintHelp();
		throw invalid_argument("Wrong command line arguments");
	}
}

void ArgsParser::PrintHelp()
{
	cout << "For ping-pong server:\n"\
			"		benchmark ping_pong\n\n"\
			"For benchmarking:\n"\
			"		benchmark host_name connection_count [-port:number] [-sync] [-pingpong]\n"\
			"	where host_name - ip address or name of the server\n"\
			"		  connection_count - count of connection to server\n"\
			"		  [-port:number] - server's port number to connect\n"\
			"		  [-sync] - creates separate thread for each connection\n"\
			"		  [-pingpong] - starts ping-pong client (for latency measuring)\n" << endl;
}

void ArgsParser::SetDefault()
{
	_connectionCount = 1;
	_isSync = false;
	_isPingPongServer = false;
	_isPingPongClient = false;
	_hostName = "127.0.0.1";
	_port = 80;
}
